import tkinter as tk
from tkinter import Label, Listbox, Scrollbar, Frame, Button, Entry, messagebox
import json
import sys
import os

# Ensure the social_system directory is in the system path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from student import Student, load_students
from bridge_service import Community, load_communities

class Application(tk.Tk):
    def __init__(self, master=None):
        super().__init__()
        self.title("Student and Community Manager")
        self.geometry("800x600")

        # Load students and communities data
        script_dir = os.path.dirname(os.path.abspath(__file__))
        students_file_path = os.path.join(script_dir, 'ressources', 'students.json')
        communities_file_path = os.path.join(script_dir, 'ressources', 'classes.json')

        self.students = load_students(students_file_path)
        self.communities = load_communities(communities_file_path)
        self.selected_student = None

        self.create_widgets()

    def create_widgets(self):
        # Frame for student list
        frame_students = Frame(self)
        frame_students.pack(side="left", fill="both", expand=True)

        label_students = Label(frame_students, text="Students")
        label_students.pack(pady=5)

        scrollbar_students = Scrollbar(frame_students)
        scrollbar_students.pack(side="right", fill="y")

        self.listbox_students = Listbox(frame_students, yscrollcommand=scrollbar_students.set)
        self.listbox_students.pack(fill="both", expand=True)
        scrollbar_students.config(command=self.listbox_students.yview)

        for student in self.students.values():
            self.listbox_students.insert("end", f"{student.full_name} ({student.username})")

        self.listbox_students.bind("<<ListboxSelect>>", self.on_student_select)

        # Frame for student details
        frame_details = Frame(self)
        frame_details.pack(side="right", fill="both", expand=True)

        self.label_full_name = Label(frame_details, text="Full Name:")
        self.label_full_name.pack(pady=5)

        self.label_interests = Label(frame_details, text="Interests:")
        self.label_interests.pack(pady=5)

        self.label_friends = Label(frame_details, text="Friends:")
        self.label_friends.pack(pady=5)

        self.scrollbar_friends = Scrollbar(frame_details)
        self.scrollbar_friends.pack(side="right", fill="y")

        self.listbox_friends = Listbox(frame_details, yscrollcommand=self.scrollbar_friends.set)
        self.listbox_friends.pack(fill="both", expand=True)
        self.scrollbar_friends.config(command=self.listbox_friends.yview)

        button_show_communities = Button(frame_details, text="Show Communities", command=self.show_communities)
        button_show_communities.pack(pady=10)

        # Add Friend Section
        frame_add_friend = Frame(frame_details)
        frame_add_friend.pack(pady=10)

        label_add_friend = Label(frame_add_friend, text="Add Friend Username:")
        label_add_friend.pack(side="left", padx=5)

        self.entry_add_friend = Entry(frame_add_friend)
        self.entry_add_friend.pack(side="left", padx=5)

        button_add_friend = Button(frame_add_friend, text="Add Friend", command=self.add_friend)
        button_add_friend.pack(side="left", padx=5)

        # Search by Interest Section
        frame_search_interest = Frame(frame_details)
        frame_search_interest.pack(pady=10)

        label_search_interest = Label(frame_search_interest, text="Search by Interest:")
        label_search_interest.pack(side="left", padx=5)

        self.entry_search_interest = Entry(frame_search_interest)
        self.entry_search_interest.pack(side="left", padx=5)

        button_search_interest = Button(frame_search_interest, text="Search", command=self.search_by_interest)
        button_search_interest.pack(side="left", padx=5)

    def on_student_select(self, event):
        selected_index = self.listbox_students.curselection()
        if selected_index:
            selected_text = self.listbox_students.get(selected_index)
            username = selected_text.split("(")[1].strip(")")
            self.selected_student = self.students[username]

            self.label_full_name.config(text=f"Full Name: {self.selected_student.full_name}")
            self.label_interests.config(text=f"Interests: {', '.join(self.selected_student.interests)}")

            self.listbox_friends.delete(0, "end")
            for friend_username in self.selected_student.relations:
                friend = self.students.get(friend_username)
                if friend:
                    self.listbox_friends.insert("end", f"{friend.full_name} ({friend.username})")

    def show_communities(self):
        community_window = tk.Toplevel(self)
        community_window.title("Communities")
        community_window.geometry("400x300")

        scrollbar_communities = Scrollbar(community_window)
        scrollbar_communities.pack(side="right", fill="y")

        listbox_communities = Listbox(community_window, yscrollcommand=scrollbar_communities.set)
        listbox_communities.pack(fill="both", expand=True)
        scrollbar_communities.config(command=listbox_communities.yview)

        for community in self.communities:
            members = ", ".join([f"{self.students[member].full_name} ({member})" for member in community.members])
            listbox_communities.insert("end", f"Community ID: {community.community_id}, Members: {members}")

    def add_friend(self):
        if not self.selected_student:
            messagebox.showwarning("Warning", "No student selected.")
            return
        
        friend_username = self.entry_add_friend.get().strip()
        if friend_username and friend_username in self.students:
            friend = self.students[friend_username]
            self.selected_student.add_friend(friend)
            self.listbox_friends.insert("end", f"{friend.full_name} ({friend.username})")
            self.entry_add_friend.delete(0, "end")
            messagebox.showinfo("Success", f"Added {friend.full_name} as a friend.")
        else:
            self.entry_add_friend.delete(0, "end")
            self.entry_add_friend.insert(0, "Invalid username")
            messagebox.showerror("Error", "Invalid username.")

    def search_by_interest(self):
        interest = self.entry_search_interest.get().strip().lower()
        if not interest:
            messagebox.showwarning("Warning", "Please enter an interest.")
            return
        
        matching_students = [student for student in self.students.values() if interest in student.interests]
        
        if not matching_students:
            messagebox.showinfo("Info", "No students found with the specified interest.")
            return
        
        result_window = tk.Toplevel(self)
        result_window.title(f"Students with Interest: {interest}")
        result_window.geometry("400x300")

        scrollbar_results = Scrollbar(result_window)
        scrollbar_results.pack(side="right", fill="y")

        listbox_results = Listbox(result_window, yscrollcommand=scrollbar_results.set)
        listbox_results.pack(fill="both", expand=True)
        scrollbar_results.config(command=listbox_results.yview)

        for student in matching_students:
            listbox_results.insert("end", f"{student.full_name} ({student.username})")

if __name__ == "__main__":
    app = Application()
    app.mainloop()